package com.wxy.ej.flow.modules.taskflow.service.nodeExecuteStrategy.strategy.in;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.config.SpringContextBaseHolder;
import com.rt.easyjava.common.utils.others.StringUtils;
import com.wxy.ej.flow.modules.taskflow.bean.TaskFlowDs;
import com.wxy.ej.flow.modules.taskflow.dto.DataDto;
import com.wxy.ej.flow.modules.taskflow.dto.NodeDto;
import com.wxy.ej.flow.modules.taskflow.facade.ShortTokenApi;
import com.wxy.ej.flow.modules.taskflow.repository.JdbcRepository;
import com.wxy.ej.flow.modules.taskflow.service.beanService.TaskFlowDsService;
import com.wxy.ej.flow.modules.taskflow.service.ds.MysqlUtils;
import com.wxy.ej.flow.modules.taskflow.service.nodeExecuteStrategy.NodeStrategy;
import com.wxy.ej.flow.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.sql.SQLException;
import java.util.*;

@Slf4j
public class InHttpStrategy extends NodeStrategy {

    @Override
    public Result action(NodeDto node, JSONObject flowDataJson, DataDto dataDto)  throws Exception{
        log.info("InHttpStrategy: ");

        String resultString = invokeHttp(node);
        dataDto.getLogList().add(resultString); // log
        Object result = null;
        if (resultString.startsWith("{")) {
            result = JSONObject.parseObject(resultString);
        }
        else if (resultString.startsWith("[")) {
            result = JSONArray.parseObject(resultString);
        }

        // 保存数据
        String inDataToStorageMapVar = node.getDefineVarName();
        dataDto.getStorageDataVarMap().put(inDataToStorageMapVar, result);

        return Result.builder(result);
    }



    protected String invokeHttp(NodeDto node)  {
        RestTemplate restTemplate =  SpringContextBaseHolder.getBean("restTemplate");
        String url = node.getHttpUrl();
        String method = node.getHttpMethod();
        String param = node.getHttpData();
        String header = node.getHttpHeader();

        // 参数
        Map<String, Object> paramMap = new HashMap<>();
        if (!StringUtils.isNull(param)) {
            paramMap = (Map) JSON.parse(param);
            if (!StringUtils.isNull(paramMap.get("method"))) {
                method = (String) paramMap.get("method");
            }
        }
        String resultJO = null;
        HttpHeaders headers = getHeaders(header);
        HttpEntity<String> formEntity = new HttpEntity<String>(param, headers);
        // method
        HttpMethod httpMethod = HttpMethod.GET;
        if (method!=null && method.equalsIgnoreCase("post")) {
            httpMethod = HttpMethod.POST;
        }
        // api
        ResponseEntity<String> response = restTemplate.exchange(url, httpMethod, formEntity, String.class);
        resultJO = response.getBody();

        String jsonStringResult = resultJO;
        if (!Strings.isBlank(jsonStringResult) && jsonStringResult.length() > 1000) {
            jsonStringResult = jsonStringResult.substring(0, 1000);
        }

        return jsonStringResult;
    }


    private HttpHeaders getHeaders(String header) {
        HttpHeaders headers = new HttpHeaders();
        if (StringUtils.isNull(header)) {
            return headers;
        }
        ShortTokenApi shortTokenApi =  SpringContextBaseHolder.getFeignBean("shortTokenApi", ShortTokenApi.class);
        JSONObject headerJo = JSONObject.parseObject(header);
        Set<String> headerKeySet = headerJo.keySet();
        Iterator<String> it = headerKeySet.iterator();
        while (it.hasNext()) {
            String key = it.next();
            String val = headerJo.getString(key);
            if (key.equalsIgnoreCase("Authorization") && org.apache.commons.lang.StringUtils.isNotBlank(val) && val.contains("jti ")) {
                String jti = org.apache.commons.lang.StringUtils.substringAfter(val, "jti ");
                String token = shortTokenApi.selectBy(jti);
                if (token==null) {
                    token = jti;
                }
                headers.add("Authorization", "Bearer "+token);
            }else{
                headers.add(key, val);
            }
        }
        return headers;
    }

}
